package com.team622.shop.gateway.filters;

import com.team622.shop.gateway.config.WhileListConfig;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {

    @Resource
    private WhileListConfig whileListConfig;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest request = exchange.getRequest();
//        String path = request.getURI().getPath();
//        log.info("请求路径为：{}",path);
//        //白名单放行
//        if(isWhiteList(path)){
//            return chain.filter(exchange);
//        }
//
//        // 从请求头中获取token
//        String token = request.getHeaders().getFirst("Authorization");
//        if(!StringUtils.hasText(token)){
//            exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
//            return exchange.getResponse().setComplete();
//        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private boolean isWhiteList(String path){
        if(path ==null){
            return false;
        }

        for (String s : whileListConfig.getWhiteList()) {
            // 匹配路径 不要用equals
            if(antPathMatcher.match(s,path)){
                return true;
            }
        }

        return false;
    }
}
